/**
 * 存储 Storage
 */
export default class Ls {
  /**
   * 获取数据
   * @param {string} key 键
   */
  get(key) {
    return new Promise(resolve => {
      wx.getStorage({
        key,
        success(res) {
          const data = JSON.parse(res.data)
          if (data.expire === null) {
            resolve(data.value)
          } else if (data.expire >= new Date().getTime()) {
            resolve(data.value)
          } else {
            this.del(key)
            resolve(false)
          }
        },
        fail() {
          resolve(false)
        }
      })
    })
  }
  /**
   * 储存数据
   * @param {string} key 键
   * @param {*} value 值
   * @param {number} expire 过期时间
   */
  set(key, value, expire = null) {
    return new Promise(resolve => {
      wx.setStorage({
        key,
        data: JSON.stringify({
          value,
          expire: expire !== null ? new Date().getTime() + expire : null
        }),
        success(res) {
          resolve(res)
        },
        fail() {
          resolve(false)
        }
      })
    })
  }
  /**
   * 删除数据
   * @param {string} key 键
   */
  del(key) {
    return new Promise(resolve => {
      wx.removeStorage({
        key,
        success(res) {
          resolve(res)
        },
        fail() {
          resolve(false)
        }
      })
    })
  }
  /**
   * 清除数据
   */
  clean() {
    return new Promise(resolve => {
      wx.clearStorage({
        success(res) {
          resolve(res)
        },
        fail() {
          resolve(false)
        }
      })
    })
  }
}